<template>
  <div v-if="order">
    <van-panel title="收货信息">
      <van-cell-group v-show="showAddress">
        <van-cell v-if="address" :title="address_title" is-link :label="address_body" @click="switchAddressSelect"></van-cell>
        <van-cell v-else title="收货地址" is-link value="设置" @click="switchAddressSelect"></van-cell>
      </van-cell-group>
    </van-panel>
    <van-panel title="订单信息" class="border-block">
      <van-card v-for="(item, index) in order.detail" :title="item.product_title" :desc="item.sku_name" :num="item.amount" :price="item.price" :thumb="item.product_image + '?imageView2/1/w/120/h/120/q/75'" :key="index" @click="onDetailClick(item)"/>
      <van-cell-group>
        <van-cell title="配送方式" value="普通快递"></van-cell>
        <van-cell title="运费" :value="'￥' + order.express_fee"></van-cell>
        <van-cell v-if="red_packet" title="优惠" :value="'-￥' + red_packet.value"></van-cell>
      </van-cell-group>
    </van-panel>
      <van-cell-group style="border-block" :border="false">
      <van-cell v-if="!red_packet" title="红包抵扣" is-link value="使用红包" @click="selectRedPacket"></van-cell>
      <van-cell v-if="red_packet" title="红包抵扣" is-link  :value="red_packet.name" @click="selectRedPacket"></van-cell>
    </van-cell-group>

    <van-cell-group class="border-block" :border="false" v-if="!show_address_edit">
      <van-field :value="customer_message" label="买家留言" type="textarea" placeholder="点击备注花色、度数、其它留言" autosize @change="inputMsg"></van-field>
    </van-cell-group>
    <van-submit-bar custom-class="mk-submit-bar" :price="finalMoney*100" buttonText="订单提交" :loading="submitStatus" @submit="submitOrder"/>
    <!-- 切换不同的地址 -->
    <van-action-sheet :show="show_address_select" position="bottom" @close="switchAddressSelect" title="收货地址选择">
      <div class="sheet-box" v-if="address_actions">
        <div class="address-sheet-item" v-for="(item, index) in address_actions" :key="index" @click="onAddressSelect(item.address)">
          <p class="address-item-title">{{item.name}}</p>
          <p class="address-item-detail">{{item.subname}}</p>
        </div>
        <div class="form-btn">
        <van-button class="mk-button" type="primary" size="normal" block="true" @click="switchAddressShow">新增地址</van-button>
        </div>
      </div>
    </van-action-sheet>
      <van-popup :show="show_red_packets" custom-style="width:100%;height:100%; background:#F5F5F5;" position="right" :overlay="false">
      <select-red-packet @not-selected="onNotSelectedRedPacket" @selected="onSelectedRedPacket" :order="order"/>
    </van-popup>
    <!-- 添加地址编辑 -->
    <van-popup :show="show_address_edit" position="bottom" @close="switchAddressShow" z-index="999">
      <div class="form">
        <van-cell-group>
          <van-cell @click="switchShowAreaSelect" value-class="address-item">
            <span class="title">收件地区</span>
            <span class="value">{{showAreaDetail || '选择收件地址'}}</span>
          </van-cell>
          <van-field :value="form.name" label="收货人" data-name="name" clearable placeholder="请输入姓名" @input="onChangeField" />
          <van-field :value="form.tel" label="联系电话" data-name="tel" clearable placeholder="请输入手机号" @input="onChangeField" />
          <van-field :value="form.address_detail" label="详细地址" data-name="address_detail" clearable placeholder="如街道、楼层、门牌号" @input="onChangeField" />
          <van-switch-cell title="默认收货地址" :checked="form.is_default" @change="changeDefault" />
          <div class="form-btn">
          <van-button class="mk-button" type="primary" size="normal" block="true" @click="saveForm">保存</van-button>
          </div>
        </van-cell-group>
      </div>
    </van-popup>
    <!-- 获得城市列表 -->
    <van-popup :show="selectArea" position="bottom" class="select-area" z-index="1000">
      <van-area v-if="area_list" :area-list="area_list" title="选中省市区" :value="form.area_code" @confirm="confirmArea" @cancel="switchShowAreaSelect" />
    </van-popup>
    <van-dialog id="van-dialog" /> 
  </div>
</template>

<script>
import Dialog from 'vant-weapp/dist/dialog/dialog'
import RedPacket from './components/select-red-packet'
import * as AddressAction from '@/api/address'
import * as OrderAction from '@/api/order'
import * as CommonAction from '@/api/common'
import Utils from '@/utils'

export default {
  components: {
    'select-red-packet': RedPacket
  },
  data () {
    return {
      product_id: '',
      order: null,
      red_packet: null,
      show_red_packets: false,
      submitStatus: false,
      showAreaDetail: null,
      show_address_select: false,
      show_address_edit: false,
      selectArea: false,
      area_list: null,
      address_list: [],
      address: null,
      showAddress: false,
      customer_message: '',
      address_actions: [],
      payForm: null,
      form: {
        is_default: true,
        area_code: ''
      }
    }
  },
  computed: {
    address_title () {
      if (!this.address) return ''
      return this.address.name + ' ' + this.address.tel
    },
    address_body () {
      if (!this.address) return ''
      return (
        this.address.province +
        ' ' +
        this.address.city +
        ' ' +
        this.address.county +
        ' ' +
        this.address.address_detail
      )
    },
    finalMoney () {
      if (!this.order) return ''
      if (!this.red_packet) return this.order.money
      if (this.order.money * 1 > this.red_packet.value * 1) return this.order.money * 1 - this.red_packet.value * 1
      return 0
    }
  },
  onShow () {
    this.show_red_packets = false
    this.show_address_edit = false
    this.selectArea = false
    this.show_address_select = false
  },
  onLoad () {
    wx.showNavigationBarLoading()
    this.red_packet = null
    this.fetchOrder()
    this.fetchAddressList()
    this.fetchArea()
  },
  methods: {
    onDetailClick (item) {
      wx.navigateTo({ url: '../product/detail?id=' + item.product_id })
    },
    selectRedPacket () {
      this.show_red_packets = true
    },
    onNotSelectedRedPacket () {
      this.show_red_packets = false
      this.red_packet = null
    },
    onSelectedRedPacket (redPacket) {
      this.show_red_packets = false
      this.red_packet = redPacket
    },
    inputMsg (event) {
      this.customer_message = event.mp.detail
    },
    onChangeField (event) {
      this.form[event.currentTarget.dataset.name] = event.mp.detail
    },
    switchAddressSelect () {
      this.show_address_select = !this.show_address_select
    },
    switchAddressShow () {
      this.showAreaDetail = ''
      this.form = {
        is_default: true,
        area_code: ''
      }
      this.show_address_edit = !this.show_address_edit
    },
    switchShowAreaSelect () {
      this.selectArea = !this.selectArea
    },
    changeDefault (e) {
      this.form.is_default = !this.form.is_default
    },
    onAddressSelect (address) {
      this.address = address
      this.show_address_select = false
    },
    addressTitle (address) {
      return address.name + ' ' + address.tel
    },
    addressBody (address) {
      return (
        address.province +
        ' ' +
        address.city +
        ' ' +
        address.county +
        ' ' +
        address.address_detail
      )
    },
    // 提交选中的地区
    confirmArea (event) {
      this.form.province = event.mp.detail.values[0].name
      this.form.city = event.mp.detail.values[1].name
      this.form.county = event.mp.detail.values[2].name
      this.form.area_code = event.mp.detail.values[2].code
      this.showAreaDetail = `${this.form.province} ${this.form.city} ${
        this.form.county
      } `
      this.switchShowAreaSelect()
    },
    saveForm () {
      if (!this.showAreaDetail) {
        wx.showToast({ title: '请选择地区', icon: 'none' })
        return
      }
      if (!this.form.name) {
        wx.showToast({ title: '姓名不能为空', icon: 'none' })
        return
      }
      if (!this.form.tel) {
        wx.showToast({ title: '手机号不能为空', icon: 'none' })
        return
      }
      if (!this.form.address_detail) {
        wx.showToast({ title: '地址不能为空', icon: 'none' })
        return
      }

      if (!Utils.validator.isMobile(this.form.tel)) {
        wx.showToast({ title: '请输入有效的手机号', icon: 'none' })
        return
      }
      AddressAction.store(this.form).then((data) => {
        this.address = data
        this.form = {}
        this.form.is_default = true
        this.switchAddressShow()
        this.switchAddressSelect()
        this.fetchAddressList()
      }).catch(err => wx.showToast({ title: err.msg, icon: 'none' }))
    },
    submitOrder () {
      if (!this.address) {
        wx.showToast({ title: '请选择收货地址', icon: 'none' })
        return
      }
      this.submitStatus = true
      let params = {
        address_id: this.address.id,
        order_id: this.$root.$mp.query.id,
        customer_message: this.customer_message
      }
      if (this.red_packet) { params.red_packet_id = this.red_packet.id }
      OrderAction.submitOrder(params)
        .then(data => {
          this.payPro(data.id)
        })
        .catch(err => {
          this.submitStatus = false
          wx.showToast({ title: err.msg, icon: 'none' })
        })
    },
    // 支付
    payPro (id) {
      OrderAction.pay(this.$root.$mp.query.id)
        .then(data => {
          this.payForm = data
          this.payMoney(id)
        })
        .catch(err => {
          this.submitStatus = false
          wx.showToast({ title: err.msg, icon: 'none' })
        })
    },
    payMoney (id) {
      let that = this
      wx.requestPayment({
        timeStamp: this.payForm.timestamp, // 时间戳
        nonceStr: this.payForm.nonceStr, // 随机字符串
        package: this.payForm.package, // 统一下单接口返回的 prepay_id 参数值
        signType: this.payForm.signType, // 加密方式
        paySign: this.payForm.paySign, // 签名
        success: function (res) {
          that.submitStatus = false
          Dialog.confirm({
            title: '提示',
            message: '您是否支付成功'
          }).then(() => {
            wx.redirectTo({ url: 'detail?id=' + id })
          }).catch(() => {
            wx.redirectTo({ url: 'detail?id=' + id })
          })
        },
        fail: function (err) {
          that.submitStatus = false
          wx.showToast({ title: '支付失败', icon: 'none' })
          console.log(err)
          wx.redirectTo({ url: 'detail?id=' + id })
        }
      })
    },
    fetchAddressList () {
      AddressAction.list()
        .then(data => {
          this.address_list = data
          let da = null
          data.map(item => {
            if (item.is_default) {
              da = item
            }
          })
          this.address_actions = data.map(item => {
            this.addressTitle(item)
            this.addressBody(item)
            return {
              name: this.addressTitle(item),
              subname: this.addressBody(item),
              address: item
            }
          })
          if (!da && data.length > 0) {
            da = data[0]
          }
          this.address = da
        })
        .catch(err => wx.showToast({ title: err.msg, icon: 'none' }))
    },
    fetchOrder () {
      OrderAction.show(this.$root.$mp.query.id)
        .then(data => {
          this.order = data
          this.product_id = data.detail[0].product_id
          wx.hideNavigationBarLoading()
        })
        .catch(err => wx.showToast({ title: err.msg, icon: 'none' }))
    },
    // 获取省市县列表
    fetchArea () {
      CommonAction.area()
        .then(data => {
          this.area_list = data
        }).catch(err => console.log(err.msg))
    }
  }

}
</script>

<style lang="less" scoped>
.address-title {
  .van-cell__title.van-cell__title {
    flex: 2;
  }
}
.srp {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  background: #f5f5f5;
}
.border-block {
  margin-top: 10rpx
}
  .form-btn{
    margin: 20rpx;
  }
.sheet-box {
  .address-sheet-item {
    padding: 10px 15px;
    border-top: 1rpx solid #F2F2F2;
    .address-item-title {
      color: #333;
      font-size: 14px;
      line-height: 1.5;
    }
    .address-item-detail {
      font-size: 12px;
      line-height: 1.5;
      color: #666;
    }
  }
  .address-sheet-item:hover,
  .address-sheet-item:active {
    background: rgb(221, 219, 219)
  }
}
</style>